<template>
	<view class="container">
		<view>共{{ questions.length }}题: 当前第{{ currentQuestionIndex + 1 }}题 ，剩余时间: {{ formatTime(remainingTime) }}</view>
		<!-- 田字格数字展示 -->
		<view class="number-grid">
			<view v-for="(number, index) in currentNumbers" :key="index"
				:class="{ 'number-item': true, 'number-item-clicked': number.clicked }" :disabled="number.clicked"
				@click="handleNumberClick(index)">{{ number.value }}</view>
		</view>
		<!-- 按钮排列 -->
		<view class="button-grid">
			<button v-for="(button, index) in buttons" :key="index" :class="button.class"
				@click="handleButtonClick(button.value)">{{ button.label }}</button>
		</view>
		<!-- 输入框 -->
		<div style="display: flex; align-items: center; gap: 5px;">
			<input v-model="inputExpression" 
					readonly="readonly"
					disabled
					placeholder="请输入表达式" 
					style="flex: 1; max-width: 90%;" />
			<label style="display: flex; align-items: center;">=24</label>
		</div>
		<!-- 下一题按钮 -->
		<button v-if="currentQuestionIndex > 0" @click="prevQuestion">上一题</button>
		<button v-if="currentQuestionIndex < questions.length - 1" @click="nextQuestion">下一题</button>
		<!-- 提交按钮 -->
		<button v-if="currentQuestionIndex === questions.length - 1" @click="submitAnswer">提交答案</button>
	</view>
	<view v-if="showResult" class="result-view">
  <view>正确率: {{ accuracy }}，正确题目数: {{ correctCount }}，错误题目数: {{ wrongCount }}</view>
  <view v-if="wrongAnswers.length > 0">
    <view>错误题目的正确答案:</view>
    <view v-for="(item, index) in wrongAnswers" :key="index">题目: {{ item.question.join(', ')}}, 答案: {{ item.correctAnswer }}</view>
  </view>
</view>
</template>

<script>

export default {
	data() {
		return {
			// 预置10组可解24点的经典题目组合
			questions: [
				[1, 2, 3, 4],
				[2, 3, 4, 5],
				[3, 4, 5, 6],
				[4, 5, 6, 7],
				[5, 6, 7, 8],
				[6, 7, 8, 9],
				[7, 8, 9, 10],
				[1, 3, 5, 7],
				[2, 4, 6, 8],
				[3, 5, 7, 9]
			],
			showResult: false,
			currentQuestionIndex: 0,
			currentNumbers: [],
			sets: [],
			inputExpression: '',
			correctCount: 0,
			totalCount: 0,
			accuracy:'',
			// 新增数组用于记录每组题目的答案
     		remainingTime: 600,
			answers: new Array(10).fill(''),
			// 按钮配置
			buttons: [
				{ label: '+', value: '+', class: 'operator-button' },
				{ label: '-', value: '-', class: 'operator-button' },
				{ label: '*', value: '*', class: 'operator-button' },
				{ label: '/', value: '/', class: 'operator-button' },
				{ label: '(', value: '(', class: 'bracket-button' },
				{ label: ')', value: ')', class: 'bracket-button' },
				{ label: '删除', value: 'delete', class: 'delete-button' },
			],
			correctCount: 0,
			wrongCount: 0,
			wrongAnswers: [],

		}
	},
	onLoad() {


		// 生成10组可解24点的数字
		const generate10Sets = () => {
			const sets = [];
			while (sets.length < 10) {
				const numbers = this.generateSolvableNumbers();
				sets.push(numbers.map(num => num.value));
			}
			return sets;
		};
		this.questions = generate10Sets().sort((a, b) => {
			for (let i = 0; i < 4; i++) {
				if (a[i] !== b[i]) {
					return a[i] - b[i];
				}
			}
			return 0;
		});
		this.loadQuestion();
		// 添加倒计时逻辑
		this.timer = setInterval(() => {
			if (this.remainingTime > 0) {
				this.remainingTime--;
			} else {
				clearInterval(this.timer);
				this.submitAnswer();
			}
		}, 1000);
	},
	
	methods: {
		// 此处省略原有 methods 中的代码，将 formatTime 方法移到此处
    calculateExpression(expr) {
      const precedence = {
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2
      };
      const applyOperator = (operators, values) => {
        const operator = operators.pop();
        const right = values.pop();
        const left = values.pop();
        switch (operator) {
          case '+': values.push(left + right); break;
          case '-': values.push(left - right); break;
          case '*': values.push(left * right); break;
          case '/': values.push(left / right); break;
        }
      };
      const tokens = expr.match(/\d+|[+\-*/()]|\S/g) || [];
      const values = [];
      const operators = [];
      for (let token of tokens) {
        if (/\d+/.test(token)) {
          values.push(parseFloat(token));
        } else if (token === '(') {
          operators.push(token);
        } else if (token === ')') {
          while (operators.length > 0 && operators[operators.length - 1] !== '(') {
            applyOperator(operators, values);
          }
          operators.pop(); // 弹出 '('
        } else {
          while (operators.length > 0 && precedence[operators[operators.length - 1]] >= precedence[token]) {
            applyOperator(operators, values);
          }
          operators.push(token);
        }
      }
      while (operators.length > 0) {
        applyOperator(operators, values);
      }
      return values.pop();
    },
		formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
      },
		getCorrectAnswer(nums) {
			const operate = (a, b, op) => {
				switch (op) {
					case '+': return a + b;
					case '-': return a - b;
					case '*': return a * b;
					case '/': return b !== 0 ? a / b : null;
				}
				return null;
			};
			const permute = (arr) => {
				if (arr.length === 0) return [[]];
				const result = [];
				for (let i = 0; i < arr.length; i++) {
					const current = arr[i];
					const remaining = arr.slice(0, i).concat(arr.slice(i + 1));
					const permutations = permute(remaining);
					for (let j = 0; j < permutations.length; j++) {
						const newPermutation = [current].concat(permutations[j]);
						result.push(newPermutation);
					}
				}
				return result;
			};
			const allPermutations = permute(nums);
			const operators = ['+', '-', '*', '/'];
			for (let perm of allPermutations) {
				for (let op1 of operators) {
					for (let op2 of operators) {
						for (let op3 of operators) {
							const expressions = [
								`(((${perm[0]}${op1}${perm[1]})${op2}${perm[2]})${op3}${perm[3]})`,
								`((${perm[0]}${op1}${perm[1]})${op2}(${perm[2]}${op3}${perm[3]}))`,
								`((${perm[0]}${op1}(${perm[1]}${op2}${perm[2]}))${op3}${perm[3]})`,
								`${perm[0]}${op1}(((${perm[1]}${op2}${perm[2]})${op3}${perm[3]}))`,
								`${perm[0]}${op1}(${perm[1]}${op2}(${perm[2]}${op3}${perm[3]}))`
							];
							// 定义自定义的表达式计算函数
							const calculateExpression = (expr) => {
							const precedence = {
							'+': 1,
							'-': 1,
							'*': 2,
							'/': 2
							};
							const applyOperator = (operators, values) => {
							const operator = operators.pop();
							const right = values.pop();
							const left = values.pop();
							switch (operator) {
							case '+': values.push(left + right); break;
							case '-': values.push(left - right); break;
							case '*': values.push(left * right); break;
							case '/': values.push(left / right); break;
							}
							};
							const tokens = expr.match(/\d+|[+\-*/()]|\S/g) || [];
							const values = [];
							const operators = [];
							for (let token of tokens) {
							if (/\d+/.test(token)) {
							values.push(parseFloat(token));
							} else if (token === '(') {
							operators.push(token);
							} else if (token === ')') {
							while (operators.length > 0 && operators[operators.length - 1]!== '(') {
							applyOperator(operators, values);
							}
							operators.pop(); // 弹出 '('
							} else {
							while (operators.length > 0 && precedence[operators[operators.length - 1]] >= precedence[token]) {
							applyOperator(operators, values);
							}
							operators.push(token);
							}
							}
							while (operators.length > 0) {
							applyOperator(operators, values);
							}
							return values.pop();
							};
							for (let expr of expressions) {
							//try {
							if (Math.abs(calculateExpression(expr) - 24) < 1e-9) {
							return expr;
							}
							//} catch (error) {
							//continue;
							//}
							}
						}
					}
				}
			}
			return null;
		},

		generateSolvableNumbers() {
			let numbers;
			do {
				// 生成4个1到13之间的随机不重复数字
				numbers = Array.from({ length: 4 }, () => Math.floor(Math.random() * 10) + 1);
				numbers = [...new Set(numbers)];
			} while (numbers.length < 4 || !this.isSolvable(numbers));
			return numbers.map(num => ({ value: num, clicked: false }));
		},
		// 判断4个数字是否能算出24的函数
		isSolvable(nums) {
			const operate = (a, b, op) => {
				switch (op) {
					case '+': return a + b;
					case '-': return a - b;
					case '*': return a * b;
					case '/': return b !== 0 ? a / b : null;
				}
				return null;
			};
			const solve = (arr) => {
				if (arr.length === 1) {
					return Math.abs(arr[0] - 24) < 1e-9;
				}
				for (let i = 0; i < arr.length; i++) {
					for (let j = 0; j < arr.length; j++) {
						if (i === j) continue;
						
						// 尝试所有可能的运算符组合，包含反向运算
						for (let op of ['+', '-', '*', '/']) {
							// 生成两种顺序的运算结果
							const results = [
								operate(arr[i], arr[j], op),
								operate(arr[j], arr[i], op)
							].filter(r => r !== null);
							
							// 处理合并后的新数组
							for (const result of results) {
								const newArr = [...arr.filter((_, idx) => idx !== i && idx !== j), result];
								if (solve(newArr)) {
									return true;
								}
							}
						}
					}
				}
				return false;
			};
			return solve(nums);
		},
		loadClass() {
			const currentAnswer = this.answers[this.currentQuestionIndex].replace("10","A");
			this.currentNumbers.forEach((number, index) => {
				const vnumber =number.value.toString().replace("10","A");
				if (currentAnswer && currentAnswer.includes(vnumber)) {
					this.$set(this.currentNumbers[index], 'clicked', true);
				} else {
					this.$set(this.currentNumbers[index], 'clicked', false);
				}
			});
		},
		loadQuestion() {
			this.currentNumbers = this.questions[this.currentQuestionIndex].map(num => ({ value: num, clicked: false }));
			//this.loadClass();
		},
		handleButtonClick(value) {
			if (value === 'delete') {
				if (this.inputExpression.endsWith('0')) {
					this.inputExpression = this.inputExpression.slice(0, -2);
				} else {
					this.inputExpression = this.inputExpression.slice(0, -1);
				}
			}
			else {
				if (value === 'clear') {
					this.inputExpression = '';
				} else {
					this.inputExpression += value;
				}
			}
			const savedInput = this.inputExpression;
			// 保存当前题号的答案
			this.answers[this.currentQuestionIndex] = savedInput;
			this.loadClass();
		},
		submitAnswer() {			
			this.calCorrent();
			
			this.correctCount = this.wrongAnswers.filter(item => item.isCorrect === 1).length;
			this.wrongCount = this.wrongAnswers.filter(item => item.isCorrect === 0).length;
			this.wrongAnswers= this.wrongAnswers.filter(item => item.isCorrect === 0);
			//this.showResult=true
			this.accuracy = Math.floor((this.correctCount / this.questions.length) * 100)+'%';
			let message = `正确率: ${this.accuracy}，正确题目数: ${this.correctCount}，错误题目数: ${this.wrongCount}`;
			if (this.wrongAnswers.length > 0) {
				message += '\r\n\n错误题目的正确答案:\n';
				this.wrongAnswers.forEach((item) => {
					message += `题目: ${item.question.join(', ')}\n 答案: ${item.correctAnswer}\n`;
				});
			}
			uni.showModal({
				title: '答题结果',
				content: message,
				showCancel: false,
				confirmText: '重新答题',
				success: (res) => {
					if (res.confirm) {
						// 重新生成题目
						const generate10Sets = () => {
							const sets = [];
							while (sets.length < 10) {
								const numbers = this.generateSolvableNumbers();
								sets.push(numbers.map(num => num.value));
							}
							return sets;
						};
						this.questions = generate10Sets().sort((a, b) => {
							for (let i = 0; i < 4; i++) {
								if (a[i] !== b[i]) {
									return a[i] - b[i];
								}
							}
							return 0;
						});
						this.currentQuestionIndex = 0;
						this.loadQuestion();
						this.inputExpression = '';
						this.answers = new Array(10).fill('');
						this.wrongAnswers =[];
						// 重置剩余时间并重新初始化计时器
						this.remainingTime = 600;
						clearInterval(this.timer);
						this.timer = setInterval(() => {
							if (this.remainingTime > 0) {
								this.remainingTime--;
							} else {
								clearInterval(this.timer);
								this.submitAnswer();
							}
						}, 1000);
					}
				}
			});
		},
		nextQuestion() {
			this.calCorrent();
			const savedInput = this.inputExpression;
			const savedNumberStates = this.currentNumbers.map(num => num.clicked);
			// 保存当前题号的答案
			this.answers[this.currentQuestionIndex] = savedInput;
			this.currentQuestionIndex = (this.currentQuestionIndex + 1) % this.questions.length;
			this.loadQuestion();
			// 从数组中获取并显示对应答案
			this.inputExpression = this.answers[this.currentQuestionIndex];
			// 仅恢复用户选择过数字的灰色蒙层状态
			//this.currentNumbers.forEach((num, index) => num.clicked = savedNumberStates[index] && this.currentNumbers[index].value === this.currentNumbers[index].value);
		},
		calCorrent(){// 验证当前组答案能否算出24
			const question = this.questions[this.currentQuestionIndex];
			const userAnswer = this.answers[this.currentQuestionIndex];
			try {
					console.log(1);
					const result = this.calculateExpression(userAnswer);
					//onst result = calculateExpression(userAnswer);
					console.log(2);
					// 调用 isSolvable 验证每组答案是否能算出24
					if (this.isSolvable(question)) {
						console.log(3);
						if (result === 24) {
							this.wrongAnswers = this.wrongAnswers.filter(item => JSON.stringify(item.question) !== JSON.stringify(question));
							this.wrongAnswers.push({ question, correctAnswer: this.getCorrectAnswer(question),isCorrect:1,currentQuestionIndex:this.currentQuestionIndex,userAnswer:userAnswer });
						} else {
							this.wrongAnswers = this.wrongAnswers.filter(item => JSON.stringify(item.question) !== JSON.stringify(question));
							this.wrongAnswers.push({ question, correctAnswer: this.getCorrectAnswer(question),isCorrect:0,currentQuestionIndex:this.currentQuestionIndex,userAnswer:userAnswer });
						}
					} else {
						console.log(4);
						this.wrongAnswers = this.wrongAnswers.filter(item => JSON.stringify(item.question) !== JSON.stringify(question));
						this.wrongAnswers.push({ question, correctAnswer: this.getCorrectAnswer(question),isCorrect:0,currentQuestionIndex:this.currentQuestionIndex,userAnswer:userAnswer });
					}
				} catch (error) {
					console.log(error);
					this.wrongCount++;
					this.wrongAnswers = this.wrongAnswers.filter(item => JSON.stringify(item.question) !== JSON.stringify(question));
					this.wrongAnswers.push({ question, correctAnswer: this.getCorrectAnswer(question),isCorrect:0,currentQuestionIndex:this.currentQuestionIndex,userAnswer:userAnswer });
				}
				console.log(this.wrongAnswers);
				//}
		},
		prevQuestion() {
			const savedInput = this.inputExpression;
			const savedNumberStates = this.currentNumbers.map(num => num.clicked);
			// 保存当前题号的答案
			this.answers[this.currentQuestionIndex] = savedInput;
			this.currentQuestionIndex = (this.currentQuestionIndex - 1 + this.questions.length) % this.questions.length;
			this.loadQuestion();
			// 从数组中获取并显示对应答案
			this.inputExpression = this.answers[this.currentQuestionIndex];
			// 仅恢复用户选择过数字的灰色蒙层状态
			//this.currentNumbers.forEach((num, index) => num.clicked = savedNumberStates[index] && this.currentNumbers[index].value === this.currentNumbers[index].value);

		},
		handleNumberClick(index) {
			if (!this.currentNumbers[index].clicked) {
				this.inputExpression += this.currentNumbers[index].value;
				this.currentNumbers[index].clicked = true;
			}
			const savedInput = this.inputExpression;
			// 保存当前题号的答案
			this.answers[this.currentQuestionIndex] = savedInput;
			this.loadClass();
		}
	},
	watch: {
		currentNumbers: {
			handler: function() {
				this.loadClass();
			},
			deep: true
		}
	}
}
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	/* height: 100vh; */
	background-color: #f5f5f5;
	padding-top: 0px;
	margin-top: 0px;
}

.number-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	grid-gap: 10px;
	margin-bottom: 10px;
}

.number-item {
	width: 160rpx;
	height: 160rpx;
	border: 2px solid #ffb6c1;
	/* 添加粉色边框 */
	border-radius: 10px;
	/* 添加圆角 */
	color: #ff0000;
	/* 设置文字颜色为红色 */
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 48rpx;
	/* 加大字体大小 */
	font-weight: bold;
}

.button-grid {
	display: flex;
	grid-gap: 10px;
	margin-bottom: 10px;
}

.button-grid button {
	height: 80rpx;
	background-color: #add8e6;
	color: #fff;
	border: none;
	font-size: 32rpx;
font-weight: bold;
}

input {
	width: 80%;
	height: 80rpx;
	margin-bottom: 10px;
	border: 1px solid #7171e6;
	/* 添加蓝色边框 */
	border-radius: 10px;
	/* 添加圆角效果 */
	padding: 0 10px;
	font-size: 32rpx;
font-weight: bold;
}

button {
	width: 80%;
	height: 80rpx;
	background-color: #90ee90;
	color: #fff;
	border: none;
	font-size: 32rpx; /* 加大字体大小 */
	font-weight: bold; /* 加粗字体 */
	margin-bottom: 10px;
}

.number-item-clicked {
	background-color: rgba(0, 0, 0, 0.3);
	/* 灰色蒙层效果 */
}

.result-view {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}
</style>